package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ljj
 * @create 2022-11-17-20:08
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //Todo 发短信
            log.info("短信验证号：{}",code);
            redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
            session.setAttribute(phone,code);
            return R.success("成功");
        }
        return R.error("失败");
    }

    @PostMapping ("/login")
    public R<User> login(@RequestBody Map user, HttpSession session){
        //user.put("code","111111");
        String  code = (String ) user.get("code");
        String phone = (String )user.get("phone");
        Object codeInsession = (String )redisTemplate.opsForValue().get(phone);
        //Object codeInsession = session.getAttribute(user.get("phone")+"");
        //codeInsession="111111";
        if (codeInsession!=null && code.equals(codeInsession)){
            LambdaUpdateWrapper<User> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            objectLambdaUpdateWrapper.eq(User::getPhone, phone);
            User one = userService.getOne(objectLambdaUpdateWrapper);
            if (one==null){
                 one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user",one.getId());
            redisTemplate.delete(phone);
           return R.success(one);
        }
        log.info("user{}",user);
        return R.error("失败");
    }
}
